<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="班级" prop="classId">
        <el-select v-model="queryParams.classId" clearable filterable placeholder="请选择班级">
          <el-option v-for="item in classList" :key="item.id" :label="item.title" :value="item.id" size="small">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="周次" prop="weekNumber">
        <el-input v-model="queryParams.weekNumber" placeholder="请输入周次" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="weeklyplanList">
      <el-table-column label="学期" align="center" prop="semsterName" />
      <el-table-column label="班级" align="center" prop="className" />
      <el-table-column label="周次" align="center" prop="weekNumber" />
      <el-table-column label="课程表" align="center" prop="imageUrl">
        <template slot-scope="scope">
          <div>
            <el-image style="width: 100px; height: 100px" :src="scope.row.imageUrl">
            </el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="重点工作" align="center" prop="educationFocus" :show-overflow-tooltip="true" min-width="90" />
      <el-table-column label="保育工作" align="center" prop="conservationFocus" :show-overflow-tooltip="true"
        min-width="90" />
      <el-table-column label="家长工作" align="center" prop="parentWork" :show-overflow-tooltip="true" min-width="90" />
      <el-table-column label="开始时间" align="center" prop="startTime" />
      <el-table-column label="结束时间" align="center" prop="endTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdateWeek(scope.row)">修改周次
          </el-button>
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)">修改详情
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-s-opportunity" @click="handleView(scope.row)">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" :before-close="cancel" :width="widths"
      append-to-body>
      <el-form v-if="isAdd == 1 || isAdd == 2" ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学期" prop="semsterId">
          <el-select v-model="form.semsterId" filterable clearable placeholder="请选择学期">
            <el-option v-for="item in semsterList" :key="item.id" :label="item.title" :value="item.id" size="small">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级" prop="classId">
          <el-select v-model="form.classId" clearable filterable placeholder="请选择班级">
            <el-option v-for="item in classList" :key="item.id" :label="item.title" :value="item.id" size="small">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="周次" prop="weekNumber">
          <el-input v-model="form.weekNumber" @input="filterNonChinese" placeholder="请输入周次" />
        </el-form-item>
        <el-form-item label="教育重点" prop="educationFocus">
          <el-input v-model="form.educationFocus" placeholder="请输入教育重点" />
        </el-form-item>
        <el-form-item label="保育工作" prop="conservationFocus">
          <el-input v-model="form.conservationFocus" placeholder="请输入保育工作" />
        </el-form-item>
        <el-form-item label="家长工作" prop="parentWork">
          <el-input v-model="form.parentWork" placeholder="请输入家长工作" />
        </el-form-item>
        <el-form-item label="活动时间" prop="time">
          <el-date-picker v-model="form.time" style="width: 100%" type="datetimerange" range-separator="至"
            format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="课程表" prop="imageUrl">
          <imageUpload v-model="form.imageUrl" :limit="1" />
        </el-form-item>
      </el-form>
      <div v-else>
        <custom-table ref="customTableRef" :tableData='tableData' :dayList='dayList'
          :dataListLeft='dataListLeft'></custom-table>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="isAdd == 1 || isAdd == 2" @click="openMessageBox">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getPlanList, addWorklyPlan, getWeekDetail, editWorklyPlan, delPlan } from "@/api/teach/weeklyplan";
import {
  getSpecialty,
} from "@/api/base/specialty";
import { selectSemster } from "@/api/base/semster";
import { selectClazz } from "@/api/base/clazz";
import { getToken } from "@/utils/auth";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import CustomTable from "@/components/CustomTable/index.vue"
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Specialty",
  components: { Treeselect, CustomTable },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 部门树选项
      deptOptions: [],
      // 专业表格数据
      weeklyplanList: [],
      // 教师数据
      teacherList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        classId: null,
        weekNumber: ''
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        semsterId: [
          { required: true, message: "学期不能为空", trigger: "blur" },
        ],
        classId: [
          { required: true, message: "班级不能为空", trigger: "blur" },
        ],
        weekNumber: [
          { required: true, message: "周次不能为空", trigger: "blur" },
        ],
        educationFocus: [
          { required: true, message: "教育重点不能为空", trigger: "blur" },
        ],
        conservationFocus: [
          { required: true, message: "保育工作不能为空", trigger: "blur" },
        ],
        parentWork: [
          { required: true, message: "家长工作不能为空", trigger: "blur" },
        ],
        educationFocus: [
          { required: true, message: "教育重点不能为空", trigger: "blur" },
        ],
        time: [
          { required: true, message: "活动时间不能为空", trigger: "blur" },
        ],
      },
      // 学期数据
      semsterList: [],
      // 班级数据
      classList: [],
      dataList: [],
      dataListLeft: {},
      widths: '500px',
      tableData: [],
      week: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      dayList: ['上午', '下午'],
      isAdd: 1//新增1,编辑2,查看3
    };
  },
  created() {
    this.getList();
    this.getSemster();
    this.getClazz();
  },
  methods: {
    filterNonChinese() {
      // 只保留中文字符
      this.form.weekNumber = this.form.weekNumber.replace(/[^\u4e00-\u9fa5]/g, '');
    },
    async getWeekDetail(row) {
      try {
        let params = {
          // classId:row.classId,
          // weekNumber:row.weekNumber,
          // semsterId:row.semsterId
          id: row.id,
        }
        const data = await getWeekDetail(params);
        this.dataList = Object.entries(data.data.right).map(([key, value]) => ({ [key]: value }));
        const arr = [];
        for (let i = 0; i < this.dataList.length; i++) {
          for (let key in this.dataList[i]) {
            this.dataList[i][key].name = this.week[i]
            arr.push(this.dataList[i][key])
            // }
          }
        }
        // 处理后端数据以适应 el-table 的数据结构
        for (const date in arr) {
          const row = {
            date: arr[date].name,
            morningActivities: arr[date].morning,
            afternoonActivities: arr[date].afternoon
          };
          this.tableData.push(row);
        }
        this.dealData(1) // 处理上午的数据
        this.dealData(2) // 处理下午 的数据

        console.log('this.tableData', this.tableData);
        this.dataListLeft = data.data.left
        // this.total = data.total;
        this.open = true
      } catch (e) {
        console.log(e)
      }
    },
    dealData(num) {
      // 获取一个星期所有morningActivities数组里面最多包含多少个对象，
      // 再把其他morningActivities里面push多少个空对象，每个morningActivities数组的长度一致
      const weekActivities = this.tableData
      let maxLength = 0;
      for (let i = 0; i < weekActivities.length; i++) {
        const activities = num == 1 ? weekActivities[i].morningActivities : weekActivities[i].afternoonActivities;
        if (activities.length > maxLength) {
          maxLength = activities.length;
        }
      }

      // 在每个数组末尾添加空对象，直到数组长度一致
      for (let i = 0; i < weekActivities.length; i++) {
        const activities = num == 1 ? weekActivities[i].morningActivities : weekActivities[i].afternoonActivities;
        while (activities.length < maxLength) {
          activities.push({
            activityType: "",
            activityName: "",
            activityTarget: ""
          });
        }
      }
    },
    /**班级*/
    async getClazz() {
      try {
        const { rows } = await selectClazz();
        this.classList = rows
      } catch (e) {
        console.log(e)
      }
    },
    /**学期*/
    async getSemster() {
      try {
        const { rows } = await selectSemster();
        this.semsterList = rows;
      } catch (e) {
        console.log(e)
      }
    },
    /** 查询周次列表 */
    getList() {
      this.loading = true;
      getPlanList(this.queryParams).then((response) => {
        this.weeklyplanList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.tableData = []
      this.$refs.form.resetFields();
      // this.customTableRefDataIn()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.isAdd = 1
      this.open = true;
      this.form = {}
      this.title = "添加周工作计划";
      this.widths = '500px'
    },
    // 修改周次
    handleUpdateWeek(row) {
      // console.log(row);
      this.isAdd = 2
      this.title = '修改周工作计划'
      this.form = row
      this.$set(this.form, 'time', [row.startTime, row.endTime]);
      this.open = true;
      this.widths = '500px'
    },
    // 查看
    handleView(row) {
      this.isAdd = 3
      this.title = '查看周工作计划'
      this.getWeekDetail(row)
      this.widths = '900px'

    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除该周计划?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delPlan(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$router.push({
        path: '/gradenSystem/editWeek',
        query: {
          classId: row.classId,
          weekNumber: row.weekNumber,
          semsterId: row.semsterId,
          weekId: row.id,
          examineStatus:row.examineStatus,
          examineUserId:row.examineUserId,
          weekPlanFileName:row.weekPlanFileName,
          weekPlanFileUrl:row.weekPlanFileUrl,
          status:row.status,

        },
      });
    },
    //customTableRef组件里2个数据的初始化
    customTableRefDataIn() {
      this.$refs['customTableRef'].currentData = {}
      this.$refs['customTableRef'].currentIndex = 0
      this.$refs['customTableRef'].currentForIs = true
      this.tableData = []
    },
    /** 提交按钮 */
    openMessageBox() {
      this.$confirm('是否同步该班级所在年级其他班级的数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // this.$message({
        //   type: 'success',
        //   message: '删除成功!'
        // });
        this.form.inType = 1
        this.submitForm()
        this.$refs.form.resetFields();
      }).catch(() => {
        this.form.inType = 0
        this.submitForm()
        this.$refs.form.resetFields();
        // this.$message({
        //   type: 'info',
        //   message: '已取消删除'
        // });
      });
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.startTime = this.form.time[0]
          this.form.endTime = this.form.time[1]
          if (this.isAdd == 1) {
            addWorklyPlan(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              // this.customTableRefDataIn()
              this.getList();
            });
          } else if (this.isAdd == 2) {
            editWorklyPlan(this.form).then(res => {
              if (res.code == '200') {
                this.open = false;
                // this.customTableRefDataIn()
                this.getList();
              }
            })
          }
        }

      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
  },
};
</script>
<style lang="scss" scoped>
.el-form {
  ::v-deep .el-select {
    width: 100%;

    .el-input {
      width: 100% !important;
    }
  }

  .el-form-item__content {
    width: 100%;

    .el-input {
      width: 100%;
    }

  }

  ::v-deep .el-date-editor {
    width: 100%;
  }
}
</style>
